<template>
    <div>
        <template v-if="route.name == 'onlineClassroom'">
            <ul class="ulList">
                <li class="list" v-for="(item, index) in dataList" :key="index" v-if="dataList.length > 0">
                    <div style="display: flex;align-items: center;height: 180px;margin: 30px 0;width: 100%;">
                        <img :src="baseUrl + item.cover" alt="" class="img">
                        <div style="flex: 1;height: 180px;margin-left: 30px;flex-direction: column;display: flex;">
                            <span style="font-size: 20px;font-weight: 700;color:#333">{{ item.courseName }}</span>
                            <span style="flex: 1;margin: 20px 20px 20px 0;font-size: 16px;color: #333;" class="ellipsis">{{
                                item.courseIntroduction }}</span>
                            <span>
                                <el-button type="primary" @click="handleStartLearn(item)">开始学习</el-button>
                                <el-button type="primary" @click="handleDown(item)" v-if="item.download == 0">下载</el-button>
                                <el-button type="primary" @click="handleExercise(item)"
                                    v-if="item.exercise == 0">随堂练习</el-button>
                                <el-button @click="handleCheckAnswer(item)" v-if="item.courseId && islogin">查看答案</el-button>
                            </span>
                        </div>
                    </div>
                </li>
            </ul>
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
                @pagination="getList" v-if="dataList.length != 0" />
            <el-empty :image-size="200" v-if="dataList.length == 0" />
        </template>
        <template v-if="route.name != 'onlineClassroom'">
            <router-view></router-view>
        </template>

        <!--操作数据 -->
        <el-dialog v-model="open" v-if="open" append-to-body title="答案列表" width="450px">
            <div style="font-weight: bold;font-size: 16px;color: #333;">请选择您要查看的答案：</div>
            <el-radio-group v-model="id" class="shuStyle" @change="changeRadio">
                <el-radio v-for="item, index in testList" :label="item.id" :key="item.id"><span
                        style="float: left;display: inline-block;font-size: 16px;">第{{ testList.length - index
                        }}次答题</span><span style="float: right;display: inline-block;font-size: 16px;">{{
    item.createTime }}</span>
                </el-radio>
            </el-radio-group>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="querySelect" :disabled="!id">确定</el-button>
                    <el-button @click="open = false">取消</el-button>
                </div>
            </template>
        </el-dialog>

        <!--操作数据 -->
        <el-dialog v-model="openVideo" v-if="openVideo" append-to-body title="视频播放" width="1000px" :show-close="false"
            :close-on-click-modal="false">
            <Xgplayer :url="playUrl" @triggerEvent="triggerEvent" />
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="openVideo = false">取消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { getAllList, getTestList } from '@/api/knowledgeLearn/online/onlineClassroom';
import useUserStore from '@/store/modules/user'
import { ElMessageBox } from 'element-plus'
import useProxyStore from '@/store/modules/proxy'
import Xgplayer from "./Xgplayer.vue"
import {useWebsocket} from "@/utils/socket"
const proxyStore = useProxyStore()

const route = useRoute();
const router = useRouter();
const userStore = useUserStore()
const baseUrl = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=";
const islogin = computed(() => !!userStore.name);
const testList = ref([]);
const open = ref(false);
const id = ref('');
const title = ref()
const data = reactive({
    queryParams: {
        page: 1,
        rows: 10,
        releaseStatus:0,
    },
    dataList: [],
    total: 0,
})
const { queryParams, dataList, total } = toRefs(data);
const openVideo = ref(false);
const playUrl = ref('');

watch(() => route, routes => {
    if (routes.name == 'onlineClassroom') {
        getAllList({ ...queryParams.value, islogin: islogin.value, releaseState: 0 }).then(response => {
            dataList.value = response.data.rows ? response.data.rows : [];
            total.value = response.data.total;
        });
    }
}, { deep: true, immediate: true });

// 判断是否登陆
function needLogin() {
    ElMessageBox.confirm('请先进行登陆！！', '消息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        // getList();
        router.push(`/login?toUrl=${location.href}`)
    }).catch(() => { })
}
// 随堂练习
function handleExercise(item) {
    if (!islogin.value) {
        // 判断是否登陆
        needLogin();
    } else {
        router.push({
            path: '/knowledgeLearn/online/onlineClassroom/practice',
            query: {
                id: item.id,
                title: item.courseName,
            }
        })
    }
}

// 查看答案
function handleCheckAnswer(item) {
    getTestList({ id: item.id }).then(res => {
        testList.value = res.data;
        id.value = '';
        open.value = true;
        title.value = item.courseName
    })
}

// 选择历史答案
function changeRadio(value) {
    id.value = value;
}

// 确定
function querySelect() {
    router.push({
        path: '/knowledgeLearn/online/practiceInClass/checkAnswer',
        query: {
            id: id.value,
            title: title.value,
        }
    })
}

// 开始学习
function handleStartLearn(item) {
    if (!islogin.value) {
        // 判断是否登陆
        needLogin();
    } else {
        openVideo.value = true;
        playUrl.value = location.origin + baseUrl + item.attachmentInfoEntity.attachId
    }
}

const triggerEvent = (value) => {
    console.log(value, '是否播放');
}

// 下载
function handleDown(item) {
    if (!islogin.value) {
        // 判断是否登陆
        needLogin();
    }
    var query = {
        attachId: item.attachmentInfoEntity.attachId,
        name: item.attachmentInfoEntity.attachName,
    }
    location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=" + encodeURIComponent(query.attachId);
}

/** 查询数据列表 */
function getList() {
    if (route.name == 'onlineClassroom') {
        console.log(islogin.value);
        // loading.value = true;
        getAllList({ ...queryParams.value, islogin: islogin.value, releaseState: 0 }).then(response => {
            // loading.value = false;
            dataList.value = response.data.rows ? response.data.rows : [];
            total.value = response.data.total;
        });
    } else {

    }
}

// WebSocket
const ws = useWebsocket()
ws.onmessage = (e) => {
    if(JSON.parse(e.data).moduleType=='courseManage'){
        getAllList({ ...queryParams.value, islogin: islogin.value, releaseState: 0 }).then(response => {
            dataList.value = response.data.rows ? response.data.rows : [];
            total.value = response.data.total;
        });
    }
  };

//页面卸载，关闭socket
onUnmounted(() => {
  ws.close();
});

// getList();
</script>

<style scoped lang="scss">
.ulList {
    padding-left: 0px !important;
    margin-top: 0px;

    li {
        list-style-type: none;
        border-bottom: 1px solid #d7d7d7;
        display: flex;
        align-items: center;

        .ellipsis {
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
        }

        .img {
            height: 180px;
            width: 300px;
            box-sizing: border-box;
            border: 1px solid #f5f5f5;
        }
    }
}

.shuStyle {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    margin-left: 30px;

    :deep(.el-radio__label) {
        width: 330px;
    }
}
</style>